<template>
  <div ref="pieRef" :style="{ height, width }" />
</template>

<script lang="ts" setup>
import * as echarts from 'echarts';
import { onBeforeMount, onBeforeUnmount, onMounted, ref } from 'vue';

const props = defineProps({
  width: {
    type: String,
    default: '100%',
  },
  height: {
    type: String,
    default: '200px',
  },
  chartData: {
    type: Object,
    default: () => {
      return [];
    },
  },
  index: {
    type: Number,
    default: 0,
  },
  title: {
    type: String,
    default: '',
  },
  color: {
    type: String,
    default: 'rgba(98, 143, 221, 1)',
  },
});

const pieRef = ref<any>(null);
const pieData = ref<any>([]);

onMounted(() => {
  pieData.value = props.chartData;
  initChart();
});

const initChart = () => {
  const myChart = echarts.init(pieRef.value);
  myChart.setOption(optionConfig());
};

// 配置参数
const optionConfig = () => {
  const colorList = [
    'rgba(98, 143, 221, 1)',
    'rgba(20, 201, 93, 1)',
    'rgba(237, 107, 107, 1)',
  ];
  const option = {
    title: {
      text: props.title,
      bottom: 0,
      left: 'center',
      textStyle: {
        fontSize: 14,
        color: '#000'
      }
    },
    tooltip: {
      trigger: 'item',
    },
    legend: {
      bottom: 'bottom',
      show: false,
    },
    series: [
      {
        name: '',
        type: 'pie',
        avoidLabelOverlap: false,
        radius: ['40%', '70%'],
        data: pieData.value,
        label: {
          //  饼图图形上的文本标签

          // normal 是图形在默认状态下的样式
          show: true,
          position: 'center',
          color: '#000',
          fontSize: 16,
          fontWeight: 'bold',
          formatter: '{b}', // {b}:数据名； {c}：数据值； {d}：百分比，可以自定义显示内容，
        },
        itemStyle: {
          // color: function (params) {
          //   // 自定义颜色
          //   return colorList[params.dataIndex];
          // },
          color: colorList[props.index],
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 40,
            fontWeight: 'bold',
          },
        },
        labelLine: {
          show: false,
        },
      },
    ],
  };
  return option;
};
</script>

<style lang="scss" scoped></style>
